import numpy as np
import matplotlib.pyplot as plt

# 设置泊松分布的参数 λ
Lambda = 4

# 生成三组服从参数为Lambda的泊松分布的随机数
possion_rnums_1 = np.random.poisson(lam=Lambda, size=1000)
possion_rnums_2 = np.random.poisson(lam=Lambda, size=10000)
possion_rnums_3 = np.random.poisson(lam=Lambda, size=100000)

# 初始化存储均值的列表
means_1 = []
means_2 = []
means_3 = []

# 计算前n个样本的均值，并存储在列表中
for i in range(1, len(possion_rnums_1) + 1):
    means_1.append(np.mean(possion_rnums_1[:i]))

for i in range(1, len(possion_rnums_2) + 1):
    means_2.append(np.mean(possion_rnums_2[:i]))

for i in range(1, len(possion_rnums_3) + 1):
    means_3.append(np.mean(possion_rnums_3[:i]))

# 转换列表为numpy数组，方便绘图（可选）
means_1 = np.array(means_1)
means_2 = np.array(means_2)
means_3 = np.array(means_3)

# 绘制样本均值随样本量变化的图像
plt.figure(figsize=(10, 6))
plt.plot(range(1, len(means_1) + 1), means_1, label='Sample Size = 1000')
plt.plot(range(1, len(means_2) + 1), means_2, label='Sample Size = 10000')
plt.plot(range(1, len(means_3) + 1), means_3, label='Sample Size = 100000')

# 绘制理论均值水平线
plt.axhline(y=Lambda, color='black', linestyle='--', label=f'Theoretical Mean = {Lambda}')

# 设置图像标题和标签
plt.xlabel('Sample Size (n)')
plt.ylabel('Sample Mean')
plt.title(f'Sample Mean Convergence for λ={Lambda}')
plt.legend()
plt.grid(True)
plt.show()